// 改造后的map.js（适配Vue，移除jQuery）
import * as maptalks from 'maptalks';
import * as h3 from 'h3-js';
import * as L from "leaflet";

export class Map {
  constructor() {
    this.layer = {
      markerLayer: null,
      dwLayer: null,
      lineLayer: null,
      dwToEndLineLayer: null,
    }
    this.mapView = null;
    this.drawtool = null;
    this.noEntryPointArr = [];
    this.noEntryIndex = null;
    this.drawPrev = null;
  }
  /**
   * 地图加载
   */
  initMap() {
    // 创建地图实例，设置中心点、缩放级别等
    this.mapView = new maptalks.Map("map", {
      center: [118.998, 31.984],
      zoom: 16,
      maxZoom: 18,
      minZoom: 3,
      spatialReference: {
        projection: 'EPSG:4326'
      },
      //添加天地图瓦片图层作为底图
      baseLayer: new maptalks.TileLayer("tile", {
        urlTemplate: 'http://t{s}.tianditu.gov.cn/DataServer?T=img_c&x={x}&y={y}&l={z}&tk=f82090d00bc356053a3a7a762bd2248d',
        subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
        tileSystem: [1, -1, -180, 90]
      })
    });

    // // 添加标注图层
    // const zj = new maptalks.TileLayer("zj", {
    //   urlTemplate: 'http://t{s}.tianditu.gov.cn/DataServer?T=cva_c&x={x}&y={y}&l={z}&tk=09772b2a6813373efd9c51d544763a01',
    //   subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
    //   tileSystem: [1, -1, -180, 90]
    // })
    // this.mapView.addLayer(zj)
    this.layer.markerLayer = new maptalks.VectorLayer("vector").addTo(this.mapView);

    // 添加绘图图层和工具
    this.drawLayer = new maptalks.VectorLayer("drawLayer").addTo(this.mapView);
    this.drawtool = new maptalks.DrawTool({
      //绘图模式
      mode: 'Polygon',
    }).addTo(this.mapView);
    // 默认禁用绘图工具
    this.drawtool.disable();

    // 设置绘图工具的样式符号，包括多边形和文本标签的样式
    this.drawtool.setSymbol([{
      lineColor: '#FF0000',           // 多边形边框颜色
      lineWidth: 3,                   // 多边形边框宽度
      polygonOpacity: 0.4,            // 多边形透明度
      polygonFill: '#DCE372',         // 多边形填充颜色
    }, {
      'textFaceName': 'sans-serif',     // 文本字体
      'textName': '{name}',         // 显示的文本内容，从geometry属性中获取name字段
      'textSize': 20,              // 文本大小
      'textFill': '#000',          // 文本颜色
    }]);
    let self = this;
    // 监听绘图结束事件
    this.drawtool.on('drawend', (data) => {
      console.log("绘图结束");
      let id = self.guid();                   // 生成唯一ID
      data.geometry.setId(id);                // 为绘制的几何图形设置ID
      data.geometry.setProperties({           // 设置几何图形属性
        name: `禁行区`                         // 设置名称为"禁行区"
      });
      this.drawLayer.addGeometry(data.geometry);     // 将绘制的几何图形添加到绘图图层
      this.drawPrev.geom = data.geometry;            // 保存当前绘制的几何图形
      this.drawPrev.value = `禁行区`;                // 保存当前绘制的值
      this.drawPrev.isDrawGeom = false;              // 设置绘制状态为false
      let mapLayers = self.mapView.toJSON().layers;  // 获取地图所有图层的JSON数据
      mapLayers.forEach((layer) => {                 // 遍历图层
        if (layer.id === 'drawLayer') {              // 找到绘图图层
          if (layer.geometries.length > 0) {         // 如果图层中有几何图形
            layer.geometries.forEach((geom) => {     // 遍历几何图形
              // 将禁行区信息保存到数组中，索引为noEntryIndex-1
              self.noEntryPointArr[self.noEntryIndex - 1] = {
                id: id,                              // 几何图形ID
                name: `禁行区`,                       // 几何图形名称
                geom: geom.feature.geometry.coordinates  // 几何图形坐标
              }
            })
          }
        }
      });
      this.drawtool.disable();              // 禁用绘图工具
    })
  }

  /**
   * 生成点
   */
  markerToMap(layerName, latlng, type, isMove, index) {
    let id = this.guid();
    let symbol = {
      markerFile: `./img/map/${type}-point.png`,
      markerWidth: 40,
      markerHeight: 40,
      markerDx: 0,
      markerDy: 20,
    }
    if (type === 'way') {
      symbol = [
        {
          markerFile: `./img/map/${type}-point.png`,
          markerWidth: 40,
          markerHeight: 40,
          markerDx: 0,
          markerDy: 0
        },
        {
          textFaceName: 'sans-serif',
          textWeight: "bold",
          textName: `途经点${index}`,
          textSize: 14,
          textFill: '#f8aa04',
          textDx: 0,
          textDy: 12,
        }
      ];
    }
    let point = new maptalks.Marker(latlng, {
      symbol: symbol,
    }).addTo(this.layer[layerName]);
    point.id = id;
    if (isMove) {
      this.mapView.panToPoint(latlng);
    }
    return point
  }

  /**
   * 绘制路线
   */
  drawRoute(layerName, coordinates, imageUrl) {
    // 清除之前的结果
    this.clearLayer(layerName);
    // 创建路线
    const line = new maptalks.LineString(coordinates, {
      symbol: {
        linePatternFile: imageUrl,
        lineWidth: 10
      }
    }).addTo(this.layer[layerName]);
    return line;
  }

  /**
   * 清除禁行区
   */
  deleteJxq(index, geom) {
    this.noEntryPointArr.splice(index - 1, 1);
    geom.remove();
  }

  /**
   * 清空图层
   */
  clearLayer(layerName) {
    if (this.layer[layerName]) {
      this.layer[layerName].clear();
    }
  }

  /**
   * 生成随机数
   */
  guid() {
    return (this.S4() + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + "-" + this.S4() + this.S4() + this.S4());
  }

  S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
}

export default {
  focusPolygonArea: function(coordinates,mapInstance) {
    if (coordinates && coordinates.length > 0 && mapInstance) {
      // 计算中心点
      let maxX = -Infinity, maxY = -Infinity, minY = Infinity, minx = Infinity;
      coordinates.forEach(coord => {
        maxX = Math.max(maxX, coord[0]);
        maxY = Math.max(maxY, coord[1]);
        minY = Math.min(minY, coord[1]);
        minx = Math.min(minx, coord[0]);
      });
      const centerX = (minx + maxX) / 2;
      const centerY = (minY + maxY) / 2;
      // 设置地图中心点
      mapInstance.mapView.setCenter([centerX, centerY]);
    }
  },
  startPolygonDrawing(mapView, onDrawEnd) {
    // 创建专门用于绘制多边形的图层
    let polygonLayer = mapView.getLayer('polygon-layer');
    if (!polygonLayer) {
      polygonLayer = new maptalks.VectorLayer('polygon-layer');
      mapView.addLayer(polygonLayer);
    }
    // 创建绘制工具
    let drawTool = new maptalks.DrawTool({
      mode: 'Polygon',
      symbol: {
        lineColor: '#ff0000',
        lineWidth: 3,
        polygonFill: '#edc89d',
        polygonOpacity: 0.3
      }
    });
    drawTool.on('drawend', (param) => {
      const geometry = param.geometry;
      // 获取多边形的坐标点
      const coordinates = geometry.getCoordinates()[0];
      // 将坐标和几何对象传递给回调函数
      if (onDrawEnd) {
        onDrawEnd(coordinates, geometry);
      }
      // 将多边形添加到图层
      polygonLayer.addGeometry(geometry);
    });
    // 添加绘制工具到地图并激活
    drawTool.addTo(mapView);
    drawTool.enable();
    return {
      polygonLayer: polygonLayer,
      drawTool: drawTool
    };
  }

}